//
//  ChatSelectImageViewController.m
//  Meboo
//
//  Created by kyo on 2023/10/20.
//

#import "ChatSelectImageViewController.h"
#import <RongCloudOpenSource/RongIMKit.h>
#import "MBChatPlayerView.h"
#import <AVFoundation/AVFoundation.h>

@interface ChatSelectImageViewController ()
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *sendBtn;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) MBChatPlayerView *playerView;
@end

@implementation ChatSelectImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"22253C");
    [self setupUI];
}

#pragma mark - Private Method
//获取视频的缩略图(第一帧)
- (UIImage *)getThumbnailImage {
    UIImage *theImage = nil;
     AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.videoUrl options:nil];
     AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
     generator.appliesPreferredTrackTransform = YES;
     NSError *err = NULL;
     CMTime time = CMTimeMake(1, 60);
     CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];

     theImage = [[UIImage alloc] initWithCGImage:imgRef];
     CGImageRelease(imgRef);
     return theImage;
}

#pragma mark - Action

- (void)sendAction {
    [self backAction];
    UIImage *firstImage = [self getThumbnailImage];
    
    RCMessage *message;
    if (self.oldImage) {
        RCImageMessage *mediaMessageContent = [RCImageMessage messageWithImage:self.oldImage];
        mediaMessageContent.full = YES; // 图片消息支持设置以原图发送
        message = [[RCMessage alloc] initWithType:ConversationType_PRIVATE
                                                    targetId:self.targetId
                                                   direction:MessageDirection_SEND
                                                     content:mediaMessageContent];
    } else {
        // 将视频保存到沙盒目录下
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *videoPath = [documentsPath stringByAppendingPathComponent:@"video.mp4"];
        NSData *videoData = [NSData dataWithContentsOfURL:self.videoUrl];
        [videoData writeToFile:videoPath atomically:YES];
        
        
        RCSightMessage *mediaMessageContent = [RCSightMessage messageWithLocalPath:videoPath thumbnail:firstImage duration:self.playerView.totalTime];
        message = [[RCMessage alloc] initWithType:ConversationType_PRIVATE
                                                    targetId:self.targetId
                                                   direction:MessageDirection_SEND
                                                     content:mediaMessageContent];
    }
    
    
    

    
    [[RCIM sharedRCIM] sendMediaMessage:message
                            pushContent:nil
                               pushData:nil
                               progress:^(int progress, RCMessage *progressMessage) {
        //媒体上传进度
    }
                           successBlock:^(RCMessage *successMessage) {
        //成功
        NSLog(@"");
        //        if (weakSelf.sendImageBlock) {
        //            weakSelf.sendImageBlock();
        //        }
    }
                             errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
        NSLog(@"");
    }
                                 cancel:^(RCMessage *cancelMessage) {
        //取消
        NSLog(@"");
    }];
}

- (void)backAction {
    [self.currentViewController dismissViewControllerAnimated:YES completion:^{
    }];
    [self.navigationController popViewControllerAnimated:YES];;
}

#pragma mark - UI
- (void)setupUI {
    
    CGFloat maxHeight = ScreenHeight-TabbarSafeBottomMargin-MBHeightScale(89)-MBHeightScale(34)-StatusBarAndNavigationBarHeight;
    CGFloat defultScale = ScreenWidth/maxHeight;
    
    
    if (self.oldImage) {
        CGFloat imageWidth = self.oldImage.size.width;
        CGFloat imageHeight = self.oldImage.size.height;
        
        if (imageWidth/imageHeight > defultScale) {
            //宽图,以宽为基准,匹配高度
            imageHeight = ScreenWidth*imageHeight/imageWidth;
            imageWidth = ScreenWidth;
        } else {
            //高图,以高为基准,匹配宽度
            imageWidth = maxHeight*imageWidth/imageHeight;
            imageHeight = maxHeight;
        }
        
        [self.view addSubview:self.imageView];
        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(self.view.mas_top).offset(MBHeightScale(34)+StatusBarAndNavigationBarHeight+maxHeight/2);
            make.width.mas_equalTo(imageWidth);
            make.height.mas_equalTo(imageHeight);
        }];
    } else {
        
        [self.view addSubview:self.playerView];
        [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.mas_equalTo(MBHeightScale(34)+StatusBarAndNavigationBarHeight);
            make.height.mas_equalTo(maxHeight);
        }];
    }

    
    [self.view addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(20));
        make.top.mas_equalTo(StatusBarAndNavigationBarHeight-MBHeightScale(35));
        make.width.height.mas_equalTo(MBHeightScale(30));
    }];
    
    [self.view addSubview:self.sendBtn];
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-TabbarSafeBottomMargin-MBHeightScale(20));
        make.right.mas_equalTo(MBWidthScale(-20));
        make.width.mas_equalTo(MBWidthScale(110));
        make.height.mas_equalTo(MBHeightScale(44));
    }];
}

#pragma mark - Setter && Getter

- (UIButton *)sendBtn {
    if (!_sendBtn) {
        _sendBtn = [UIButton leftimageAndRighttitlePatternWithImage:@"chat_send_image" AndMargin:MBWidthScale(7) AndTitle:@"Send" AndTitleFont:MBHelFontSizeScale(18) AndTitleColor:HEXS(@"22253C")];
        _sendBtn.backgroundColor = HEXS(@"8EBBFF");
        _sendBtn.layer.cornerRadius = MBHeightScale(44/2);
        [_sendBtn addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [UIImageView new];
        _imageView.image = self.oldImage;
    }
    return _imageView;
}

- (UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [[UIButton alloc] init];
        _backBtn.layer.cornerRadius = MBHeightScale(30/2);
        [_backBtn setImage:ImageWithName(@"chat_back") forState:0];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}
- (MBChatPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [[MBChatPlayerView alloc] initWithUrl:self.videoUrl];
    }
    return _playerView;
}
@end

